package com.itheima.alipay.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.itheima.alipay.bean.AlipayBean;
import com.itheima.alipay.config.AliPayConfig;
import com.itheima.alipay.service.AliPayService;
import com.itheima.entity.Order;
import com.itheima.mapper.ProductMapper;

@Service
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public String aliPay(AlipayBean alipayBean) throws Exception {

        // 幂等校验, 同一个订单号不能重复支付
        checkIdempotent(alipayBean);

        // 1、获得初始化的AlipayClient
        //AlipayClient alipayClient = getAlipayClient();

        // 2、设置请求参数
        AlipayTradePagePayRequest pagePayRequest = new AlipayTradePagePayRequest();

        // 异步通知URL
        pagePayRequest.setNotifyUrl(aliPayConfig.getNOTIFY_URL());

        // 页面跳转同步通知页面路径
        pagePayRequest.setReturnUrl(aliPayConfig.getRETURN_URL());

        // 支付所需参数
        pagePayRequest.setBizContent(JSON.toJSONString(alipayBean));

        // 3、请求支付宝进行付款，并获取支付结果
        AlipayTradePagePayResponse payResponse = alipayClient.pageExecute(pagePayRequest);

        String body = "";
        if (payResponse.isSuccess()) {
            // 响应为form表单格式, 前端嵌入处理并自动提交表单后跳转到支付宝的扫码支付页面
            body = payResponse.getBody();
        }

        return body;
    }

    @Override
    public void checkSign(HttpServletRequest request) throws Exception {
        Map<String, String> params = getParamsMap(request);

        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfig.getALIPAY_PUBLIC_KEY(), "utf-8",aliPayConfig.getSIGN_TYPE());
        if (signVerified) { // 验证成功

            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")) {
                // 支付成功， 且该支付功能不支持退款
            } else if (trade_status.equals("TRADE_SUCCESS")){
                // 支付成功， 且该支付功能（电脑网站支付）支持退款
            }

        } else { // 验证失败

        }
    }

    @Override
    public String tradePagePay(Long productId) {

        // 创建订单
        Order order = createOrder(productId);

        // 封装参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl("");
        request.setReturnUrl("");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", order.getNo());
        bizContent.put("total_amount", order.getPrice());
        bizContent.put("subject", "测试商品");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());

        // 异步通知URL
        //request.setNotifyUrl(aliPayConfig.getNOTIFY_URL());

        // 页面跳转同步通知页面路径
        //request.setReturnUrl(aliPayConfig.getRETURN_URL());


        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        String formStr = "";
        if (response.isSuccess()) {
            // 响应为form表单格式, 前端嵌入处理并自动提交表单后跳转到支付宝的扫码支付页面
            formStr = response.getBody();
        }
        return formStr;
    }

    private Order createOrder(Long productId) {
        Order order = new Order();
        order.setNo(UUID.randomUUID().toString());
        order.setPrice(new BigDecimal("0.01"));
        order.setProductId(productId);
        order.setStatus(0);
        return order;
    }

    private void checkIdempotent(AlipayBean alipayBean) {

    }


    private Map<String, String> getParamsMap(HttpServletRequest request) {
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }
}
